package com.example.imbmq80ai.config;

/**
 * @author sharloon
 * @date 2023/6/18
 */

import com.ibm.mq.jms.MQQueueConnectionFactory;

import javax.jms.*;

public class MQReceiver {

    private static final String QUEUE_NAME = "QUEUE.NAME";

    public static void main(String[] args) {

        try {

            MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory();
            connectionFactory.setHostName("localhost");
            connectionFactory.setPort(1414);
            connectionFactory.setQueueManager("QM1");
            connectionFactory.setChannel("DEV.APP.SVRCONN");

            Connection connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(QUEUE_NAME);

            MessageConsumer consumer = session.createConsumer(queue);

            Message message = consumer.receive(1000);

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println("Received message: " + textMessage.getText());
            } else {
                System.out.println("Received other type of message: " + message.getClass().getName());
            }

            consumer.close();
            session.close();
            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        }

    }

    public static void main2(String[] args) {

        try {

            MQQueueConnectionFactory connectionFactory = new MQQueueConnectionFactory();
            connectionFactory.setHostName("localhost");
            connectionFactory.setPort(1414);
            connectionFactory.setQueueManager("QM1");
            connectionFactory.setChannel("DEV.APP.SVRCONN");

            Connection connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(QUEUE_NAME);

            MessageProducer producer = session.createProducer(queue);

            TextMessage message = session.createTextMessage("Hello, world!");

            producer.send(message);

            System.out.println("Sent message: " + message.getText());

            producer.close();
            session.close();
            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        }

    }
}

